'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  async login() {
    this.ctx.body = 'hello';
  }
  async register() {
    // 判断是否已被占用
    const { ctx, service } = this;
    const name = ctx.request.body.name;
    const password = ctx.request.body.password;
    const result = await service.home.checkUser({
      name
    })
    if(result.code === 0) {
      this.ctx.body = result
    } else {
      if(result.isExists) {
        // 已存在
        this.ctx.body = {
          code: 10001,
          msg: '此用户名已被占用'
        }
      } else {
        // 不存在，继续注册
        const registerRes = await service.home.register({name, password})
        ctx.body = registerRes
      }

    }
    console.log('查询结果', result)
    // if(result.isRegister) {
    //   // 没有被注册过
    //   // 写入数据库
    //   await this.service.home.register();
    // } else {
    //   this.ctx.body = {
    //     code: 0,
    //     msg: '已注册'
    //   }
    // }
  }
}

module.exports = HomeController;
